package binpacking.algorithms;

import java.util.List;
import binpacking.model.*;

public class FirstFit {
	protected List<Block> blocks;
	private BinContainer binContainer;
	private int binSize;
	
	public FirstFit( List<Block> l, BinContainer binContainer, int binSize ) {
		this.blocks = l;
		this.binContainer = binContainer;
		this.binSize = binSize;
	}
	
	public void doFirstFit() {
		
		while(blocks.size() > 0) {
			Block block = blocks.remove(0);
			int binIndex = 0;
			
			while( binIndex < binContainer.getBins().size() ){
				
				Bin bin = binContainer.getBins().get(binIndex);
				
				if(bin.storageAvailable( block.getSize() ) ){
					bin.addBlock( block );
					block.place();
					break;
				} else {
					binIndex++;
				}
				
			}
			if( !block.isPlaced() ) {
				Bin bin = new Bin(binSize);
				bin.addBlock( block );
				block.place();
				binContainer.addBin( bin );
			}
		}
	}
	
	public String getResult() {
		return "Bins used: " + binContainer.getBins().size() + "\n" + binContainer.getVisualRepresentation();
	}
}
